package com.feinno.bug.actcache.service.impl;

import com.feinno.bug.actcache.entity.UserMSGVo;
import com.feinno.bug.actcache.mapper.UserMSGMapper;
import com.feinno.bug.actcache.service.MyRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zcy
 * @Description
 * @Date: 20:51 2018/11/2
 */
@Component
public class Task {

    @Autowired
    private UserMSGMapper mapper;

    private static final Logger logger = LoggerFactory.getLogger(Task.class);

    private static volatile ExecutorService executorService;

    static {
        executorService = new ThreadPoolExecutor(15, 15,
                0L, TimeUnit.SECONDS,
                // 该配置的策略：能够减缓新任务的提交速度
                new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());
    }

    private static final String DIC_KEY = "OSS:RES:PHONE:";
    private static final String DIC_KEY_GROUP = "OSS:RES:PHONEGROUP:";

    public void mytask() {
        int x = 1;
        long start = System.currentTimeMillis();
        List<UserMSGVo> list = mapper.getmax(x);
        logger.info("max siez is {}", list.size());
        for (int i = 0; i < list.size(); i++) {
            UserMSGVo userMSGVo = list.get(i);
            executorService.submit(new MyRunner(DIC_KEY, i, userMSGVo.getPhone(), userMSGVo.getGroup_id()));
        }
        List<UserMSGVo> list1 = mapper.getmin(x);
        logger.info("min siez is {}", list1.size());
        for (int i = 0; i < list1.size(); i++) {
            UserMSGVo userMSGVo = list1.get(i);
            executorService.submit(new MyRunner(DIC_KEY_GROUP, i, userMSGVo.getPhone(), userMSGVo.getGroup_id()));
        }
        executorService.shutdown();
        while (true) {
            if (executorService.isTerminated()) {
                System.out.println("所有的子线程都结束了！");
                long end = System.currentTimeMillis();
                logger.info("耗时:{} ms", end - start);
                break;
            }
        }
    }

}
